package com.simlink.sns.service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.simlink.sns.util.Property;

@Service("mailService")
public class MailService {

	static {
		String classpath = MailService.class.getClassLoader().getResource("").getPath();
		templateGroup = new StringTemplateGroup("mailTemplates", classpath + "/mailTemplates");
	}

	public static StringTemplateGroup templateGroup;

	@Value("${mail.from}")
	public static String MAIL_FROM;
	@Value("${domain.name}")
	public static String DOMAIN_NAME;
	@Value("${domain.port}")
	public static String DOMAIN_PORT;
	@Value("${domain.context}")
	public static String DOMAIN_CONTEXT;

	public static String getActivateContext() {
		return "http://" + DOMAIN_NAME + DOMAIN_PORT + DOMAIN_CONTEXT + "/account/activation/";
	}

	public static String getRRestPwdContext() {
		return "http://" + DOMAIN_NAME + DOMAIN_PORT + DOMAIN_CONTEXT + "/account/resetpwd";
	}

	private void sendMail(String to, String subject, String body) {
		JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
		MimeMessage mail = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(mail, true, "utf-8");
			helper.setFrom(MAIL_FROM);
			helper.setTo(to);
			helper.setSubject(subject);
			helper.setText(body, true);
			mailSender.send(mail);
		} catch (MessagingException e) {
			e.printStackTrace();
		}

	}

	/**
	 * send activation mail to
	 * 
	 * @param to
	 */
	public void sendAccountActivationEmail(String to, String key) {
		// String body = "<a
		// href='"+ACTIVATE_CONTEXT+key+"?email="+to+"'>激活链接</a>";
		StringTemplate activation_temp = templateGroup.getInstanceOf("activation");
		activation_temp.setAttribute("img_base_url", Property.IMG_BASE_URL);
		activation_temp.setAttribute("email", to);
		activation_temp.setAttribute("href", getActivateContext() + key + "?email=" + to);
		activation_temp.setAttribute("link", getActivateContext() + key + "?email=" + to);
		sendMail(to, "OSF账户激活", activation_temp.toString());
	}

	/**
	 * send change password link to
	 * 
	 * @param to
	 */
	public void sendResetPwdEmail(String to, String key) {

		StringTemplate activation_temp = templateGroup.getInstanceOf("resetpwd");
		activation_temp.setAttribute("img_base_url", Property.IMG_BASE_URL);
		activation_temp.setAttribute("href", getRRestPwdContext() + "?key=" + key + "&email=" + to);
		activation_temp.setAttribute("link", getRRestPwdContext() + "?key=" + key + "&email=" + to);

		sendMail(to, "OSF账户密码重置", activation_temp.toString());
	}
}
